
package com.wyzz.hr.base.quartz;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;

import com.wyzz.hr.base.FileOperate;
import com.wyzz.hr.bo.BackupRBo;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.DatabaseSysConfigManager;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;

public class DatabaseBackupService {

	public DatabaseBackupService() {
		fileConfigManager = PropertiesFileConfigManager.getInstance();
	}

	public void executeBackup() {
		String sqlBinPath = fileConfigManager.getProperty(
				"sys.security.sqlbin.path").trim();
		if (StringUtils.isEmpty(sqlBinPath))
			sqlBinPath = (new StringBuilder()).append(getHomePath()).append(
					"/mysql/bin").toString();
		String sqlCmdStr = FileOperate.sqlCmdCompose("mysqldump");
		String fileName = (new StringBuilder()).append("backup-").append(
				getDateDb()).append(".sql").toString();
		String floaderPath = (new StringBuilder()).append(getHomePath())
				.append(
						fileConfigManager
								.getProperty("sys.security.backup.path"))
				.toString();
		String filePath = (new StringBuilder()).append(floaderPath).append(
				fileName).toString();
		BackupRBo backupRBo = (BackupRBo) SpringBeanFactory
				.getBean("backupRBo");
		System.out.println(sqlBinPath + "=============" + filePath
				+ "============" + sqlCmdStr);
		boolean backupresult = backupRBo.execSqlCmd(changePath(sqlBinPath),
				changePath(filePath), sqlCmdStr);
		if (backupresult)
			deleteBackupFiles(floaderPath);
	}

	private String getDateDb() {
		SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		String mydate = sp.format(new Date());
		return mydate;
	}

	private String changePath(String original) {
		char chars[] = original.toCharArray();
		for (int i = 0; i < chars.length; i++)
			if (chars[i] == '\\')
				chars[i] = '/';
		return (new String(chars)).replaceAll("//", "/");
	}

	private void deleteBackupFiles(String floadorPath) {
		File folder = new File(floadorPath);
		int defaultCopies = 30;
		if (folder.isDirectory()) {
			String files[] = folder.list();
			String copies = DatabaseSysConfigManager.getInstance().getProperty(
					"sys.backup.copies");
			if (StringUtils.isNotEmpty(copies))
				defaultCopies = Integer.parseInt(copies);
			if (files.length <= defaultCopies)
				return;
			Arrays.sort(files);
			int loopSize = files.length - defaultCopies;
			for (int i = 0; i < loopSize; i++)
				(new File((new StringBuilder()).append(floadorPath).append(
						files[i]).toString())).delete();

		}
	}

	public String getHomePath() {
		String path = "";
		String backupPath = fileConfigManager
				.getProperty("sys.security.backup.path");
		try {
			File f = (new PropertiesConfiguration("sys_config.properties"))
					.getFile();
			f = f.getParentFile().getParentFile().getParentFile()
					.getParentFile();
			path = f.getAbsolutePath();
			if (!(new File((new StringBuilder()).append(path).append("/file/")
					.append(backupPath).toString())).exists())
				(new File((new StringBuilder()).append(path).append("/file/")
						.append(backupPath).toString())).mkdirs();
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
		return (new StringBuilder()).append(path).append("/file/").toString();
	}

	private PropertiesFileConfigManager fileConfigManager;
}
